package com.springboot.elaticsearch.demo.service.impl;

import com.alibaba.fastjson.JSON;
import com.springboot.elaticsearch.demo.service.ContentService;
import com.springboot.elaticsearch.demo.utils.HtmlParseUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.MatchPhraseQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.springboot.elaticsearch.demo.pojo.Content;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: jxm
 * @Description: 业务编写
 * @Date: 2023/2/28 21:54
 * @Version: 1.0
 */
@Service
public class ContentServiceImpl implements ContentService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public boolean saveData(String keyword) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("60s");

        List<Content> contents = HtmlParseUtil.parseJD(keyword);

        for (int i = 0; i < contents.size(); i++) {
            bulkRequest.add(new IndexRequest("jd_goods")
            .source(JSON.toJSONString(contents.get(i)), XContentType.JSON)
            );
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);

        return !bulk.hasFailures();
    }

    @Override
    public List<Map<String,Object>> search(String keyword,Integer pageNo,Integer pageSize)  throws IOException {
        SearchRequest searchRequest = new SearchRequest("jd_goods");
        //构造条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        MatchPhraseQueryBuilder matchPhraseQuery = QueryBuilders.matchPhraseQuery("name", keyword);
        sourceBuilder.query(matchPhraseQuery);

        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        //分页
        sourceBuilder.from(pageNo);
        sourceBuilder.size(pageSize);
        //高亮设置
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        //设置高亮字段
        highlightBuilder.field("name");
        //关闭多个字段高亮
        highlightBuilder.requireFieldMatch(false);
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        sourceBuilder.highlighter(highlightBuilder);
        //加入查询条件
        searchRequest.source(sourceBuilder);
        SearchResponse searchResult = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);


        List<Map<String,Object>> result = new ArrayList<>();
        SearchHits hits = searchResult.getHits();
        //
        System.out.println("================="+hits.getTotalHits().value);

        for (SearchHit hit : hits) {
            //原来的结果
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            // 高亮字段
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField name = highlightFields.get("name");
            //替换（将原来的字段换位高亮字段）
            if(name!=null){
                Text[] fragments = name.getFragments();
                StringBuffer newName = new StringBuffer();
                for (Text fragment : fragments) {
                    newName.append(fragment);
                }
                sourceAsMap.put("name",newName.toString());
            }
            result.add(sourceAsMap);
        }

        return result;
    }

}
